package com.roamer.validator.time;

import com.roamer.validator.MatchType;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 匹配
 *
 * @author roamer
 * @version V1.0
 * @date 2019/8/29 3:40 下午
 */
public class MatchTimeContext {

    private final MatchTimeStrategy strategy;

    private static final Map<MatchType, MatchTimeStrategy> COMPARATOR_MAP;

    static {
        Map<MatchType, MatchTimeStrategy> map = new HashMap<>(5);
        map.put(MatchType.eq, (fromTime, currentTime) -> fromTime - currentTime == 0);
        map.put(MatchType.gt, (fromTime, currentTime) -> fromTime - currentTime > 0);
        map.put(MatchType.ge, (fromTime, currentTime) -> fromTime - currentTime >= 0);
        map.put(MatchType.lt, (fromTime, currentTime) -> fromTime - currentTime < 0);
        map.put(MatchType.le, (fromTime, currentTime) -> fromTime - currentTime <= 0);
        // 设置为不可变Map
        COMPARATOR_MAP = Collections.unmodifiableMap(map);
    }

    public MatchTimeContext(MatchType typeEnum) {
        this.strategy = COMPARATOR_MAP.get(typeEnum);
    }

    /**
     * 执行匹配
     *
     * @param fromTime    时间
     * @param currentTime 当前时间
     *
     * @return {@code false}
     */
    public boolean executeMatches(long fromTime, long currentTime) {
        return strategy.matches(fromTime, currentTime);
    }


}
